<template>
  <div class="l">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            @clear="getUserList"
            clearable
            v-model="queryinfo.query"
            class="input-with-select"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="编号" prop="id"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="电子邮箱" prop="email"></el-table-column>
        <el-table-column label="手机" prop="mobile"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="child">
            <el-switch
              v-model="child.row.mg_state"
              @change="statuschange(child.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="child">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              v-model="child.row.id"
              @click="showModiyUserDialog(child.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUserById(child.row)"
            ></el-button>
            <el-tooltip
              effect="drak"
              placement="top"
              content="分配角色"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryinfo.total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="adddialogClosed()"
    >
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button @click="adduser()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="ModifyDialogVisible"
      @close="editdialogClosed()"
    >
      <el-form
        :model="editUserForm"
        :rules="userFormRules"
        ref="edituserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ModifyDialogVisible = false">取消</el-button>
        <el-button @click="Modifyuser()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
 
<script>
export default {
  data () {
    var checkemail = (rule, value, rb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) return rb()
      return rb(new Error('邮箱格式不正确'))
    }
    return {
      queryinfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      addDialogVisible: false,
      userForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      userFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: 'blur' },
          { min: 3, max: 6, message: "长度在3~6个字符", trigger: 'blur' }

        ],
        password: [
          { required: true, message: "请输入用户名", trigger: 'blur' },
          { min: 6, max: 15, message: "长度在6~15个字符", trigger: 'blur' }

        ],
        email: [
          { required: true, message: "请输入电子邮箱", trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }

        ],
      },
      ModifyDialogVisible: false,
      editUserForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: { 
     async   delUserById(r) {
        console.log(r)

      const res=await this.$confirm('确认删除该记录吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error)
        console.log(res)
      },
    Modifyuser () {
      this.$refs.edituserFormRef.validate(async v => {
        if (v) {
          const { data: res } = await this.$http.put(`users/${this.editUserForm.id}`, { mobile: this.editUserForm.mobile, email: this.editUserForm.email })
          if (res.meta.status != 200)
            return this.$message.warning("更新失败")
          this.$message.success(res.meta.msg)
          this.ModifyDialogVisible = false
          this.getUserList()
        }
      })
    },
    async showModiyUserDialog (r) {
      //方法一
      //this.editUserForm=r
      //方法二
      const { data: res } = await this.$http.get(`users/${r.id}`)
      if (res.meta.status !== 200) {
        this.$message.warning("查询失败")
        return
      }
      this.editUserForm = res.data
      this.ModifyDialogVisible = true


    },
    adduser () {


      this.$refs.userFormRef.validate(async v => {

        if (v) {
          const { data: res } = await this.$http.post('users', this.userForm)

          if (res.meta.status != 201) {
            this.$message.warning("创建失败")

          } else {
            this.$message.success(res.meta.msg)
            this.addDialogVisible = false
            this.getUserList()
          }
        }
      })

    },
    adddialogClosed () {

      this.$refs.userFormRef.resetFields()
      console.log('close')
    },
    editdialogClosed () {
      this.$refs.edituserFormRef.resetFields()

    },
    async statuschange (v) {
      //const { data: res } = await this.$http.put(`users.cgi/${v.id}/state/${v.status}`)
      const { data: res } = await this.$http.put(`users/${v.id}/state/${v.mg_state}`)
      if (res.meta.status === 200) {
        this.$message.success("更新成功")
      } else {
        v.status = !v.status
        this.$message.error("更新失败")
      }
    },
    handleSizeChange (pagesize) {
      this.queryinfo.pagesize = pagesize
      this.getUserList()
    },
    handleCurrentChange (currentpage) {
      this.queryinfo.pagenum = currentpage
      this.getUserList()
    },
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryinfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！');
      }
      this.userlist = res.data.users
      this.queryinfo.total = res.data.total
    }
  }
}
</script>
<style lang="less" scoped>
</style>
